package com.atstudy.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2022/12/30 14:45
 * @copyright: 博为峰
 */
public class ServerSocketChannelDemo {
    public static void main(String[] args) throws IOException {
        //创建服务器端对象
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //绑定监听端口
        serverSocketChannel.bind(new InetSocketAddress(8080));
        //设置非阻塞
        serverSocketChannel.configureBlocking(false);
        //创建selector多路复用器
        Selector selector = Selector.open();
        //注册到selector多路复用器，设置接收连接事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            //监听所有注册到selector上的事件
            int select = selector.select();

            if (select == 0) {
                continue;
            }

            //获取所有可用的channel
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                //获取其中一个可用channel
                SelectionKey selectionKey = iterator.next();
                //从set集合中删除当前selectionKey
                iterator.remove();

                //Accept状态的Channel
                if (selectionKey.isAcceptable()) {
                    HandleAccept(serverSocketChannel, selector);
                    //Readable事件触发
                } else if (selectionKey.isReadable()) {
                    HandleRead(selectionKey);
                }
            }
        }
    }

    public static void HandleRead(SelectionKey selectionKey) throws IOException {
        System.out.println("有客户端向服务器端发数据了");
        //字节缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //客户端连接
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        //len读到的字节数
        int len = socketChannel.read(byteBuffer);
        if (len != -1)
            System.out.println("从客户端读取的数据：" + new String(byteBuffer.array(), 0, len));

        //写数据到客户端
        ByteBuffer buffer = ByteBuffer.wrap("hi client".getBytes());
        socketChannel.write(buffer);
        selectionKey.interestOps(SelectionKey.OP_READ);

    }

    public static void HandleAccept(ServerSocketChannel serverSocketChannel, Selector selector) throws IOException {
        System.out.println("有客户端连接服务器端了");
        //接收客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //注册socketChannel到selector上，，设置要处理的读事件
        socketChannel.register(selector, SelectionKey.OP_READ);
    }
}
